package com.simple.orm.agreement.process;

import com.simple.orm.agreement.annotation.Describe;
import com.simple.orm.agreement.manager.impl.ProtocolManager;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

public abstract class AbstractReadProcess<T> implements ReadProcess<T> {

    protected DataInputStream dataInputStream;

    protected DescribeEvent describeEvent;

    @Override
    public T readFrom(byte[] data, boolean isPackage) throws IOException {
        dataInputStream = new DataInputStream(new ByteArrayInputStream(data));
        if (isPackage) {
            int len = dataInputStream.readInt();
            System.out.printf("总长度：%s%n", len);
        }
        int flag = dataInputStream.readInt(); // 协议类型
        Class<?> aClass = ProtocolManager.getInstance().lookup(flag);
        if (aClass == null) {
            throw new IllegalArgumentException("未知的协议");
        }
        Describe describe = aClass.getDeclaredAnnotation(Describe.class);
        if (describe != null) {
            if (describeEvent != null) describeEvent.event(describe.value());
        }
        return parse(aClass);
    }

    @Override
    public void close() throws IOException {
        if (dataInputStream != null) dataInputStream.close();
    }

    /**
     * 获取已注册的描述事件处理器，默认为null
     *
     * @return 描述事件处理器
     */
    public DescribeEvent getDescribeEvent() {
        return describeEvent;
    }

    /**
     * 注册描述事件处理器
     *
     * @param describeEvent 描述事件处理器
     */
    public void setDescribeEvent(DescribeEvent describeEvent) {
        this.describeEvent = describeEvent;
    }

    /**
     * 通过协议的映射对象，分析输入流中的数据，并将其映射到实体对象中
     *
     * @param aClass 实体对象，类对象
     * @return 实体对象
     */
    protected abstract T parse(Class<?> aClass);
}
